One moment please...
 
 
Exact Synergy Enterprise   
 

How to Consume Binary and Document Attachment Web Services

How-to: Consuming the Binary and Document Attachment Web Services

Introduction

To consume Document Attachment service, the software developers need to consume the Binary service too. Both services are working tightly together.

This document provides a step-by-step guide to do this using Microsoft Visual Studio 2008 as an example.

Button

Not applicable.

Description

  1. Open Microsoft Visual Studio 2008.
  2. Create a new project with the following information:
  • Project type: Expand Visual Basic, and then click Windows.
  • Templates: Windows Forms Application.
  • Name: TestApplication.

  1. Add a service reference to the Binary service and Document Attachment service:
  • Right-click on the TestApplication project, and then click on Add Service Reference…
  • In the Address box, enter a valid service URL for Binary service.
    For example: http://localhost/Synergy/Services/Exact.Entity.Binary.svc and then click Go.
  • In the Namespace box, type EntityBinary.



  • In the Address box, enter a valid service URL for Document Attachment service.
    For example: http://localhost/Synergy/Services/Exact.Entity.DocumentAttachment.svc and then click Go.
  • In the Namespace box, type EntityDocumentAttachment.

  1. Open the app.config and increase the size of maxBufferSize and maxReceivedMessageSize. You can change the size at anytime in order to receive the information successfully from the service. The default size might be insufficient for the entity services.

  1. Open the Form1 class in the Designer window.
  • In this example, extend Form1 by adding OpenFileDialog control, more buttons, labels, text boxes, and check boxes.
    <OpenNew> button is not designed in this test application because there is no default value returned from Document Attachment service.

     
  1. Open the Form1 class in the Code Editor window and add the following code:
  • Declare variables that will hold the Entity Binary object and Entity Document Attachment object.

Private binaryClient As New EntityBinary.BinaryClient

Private binaryData As EntityBinary.BinaryData

Private docAttachmentClient As New EntityDocumentAttachment.DocumentAttachmentClient

Private docAttachmentData As EntityDocumentAttachment.DocumentAttachmentData

  • In this example, set client credential as Impersonation.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

      binaryClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation

      docAttachmentClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation
End Sub

  • Alternate way of setting the credential is to pass a valid username, password and domain to network credential.

binaryClient.ChannelFactory.Credentials.Windows.ClientCredential = New System.Net.NetworkCredential("username", "password", "exact-software")


docAttachmentClient.ChannelFactory.Credentials.Windows.ClientCredential = New System.Net.NetworkCredential("username", "password", "exact-software")

  • There are 3 important elements for each of the properties: Value, IsDirty, and IsNothing.
    • Value is the value of the property.
    • IsDirty is the flag that a property has been changed. All changed properties (including IsNothing=True) must set IsDirty to true.
    • IsNothing is the flag to set a property to perceive data as NULL.

  • Add code to <Browse> button in order to retrieve the attachment that will be uploaded as an Exact Synergy Enterprise document.
    Click button to create an item by:

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click

      If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

            If OpenFileDialog1.FileNames.Count > 0 Then

                  For Each selectedFilenamePath As String In OpenFileDialog1.FileNames

                        txtUploadFilePath.Text = selectedFilenamePath

                  Next

            Else

                  txtUploadFilePath.Text = OpenFileDialog1.FileName

            End If

      End If
End
Sub

  • Before add code to <Create>, <Save>, <Update>, create a Private Sub Function UploadOperation().


Private Sub UploadOperation(ByVal operation As String)

      Dim chunkSize As Long = 50 * 1024 '50KB

      Dim fileInfo As FileInfo = Nothing

      Dim fileLength As Integer = 0

 

      '*** Call Binary Service ***

      For Each FilePath As String In OpenFileDialog1.FileNames

      Try

            'Get upload attachment information

            fileInfo = New FileInfo(FilePath)

            Dim fileSizeInBytes As Long = fileInfo.Length

 

            Using iStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read)

                  'Call binary service to create a message header

                  binaryData = New EntityBinary.BinaryData

                  binaryData = binaryClient.Create(binaryData)

 

                  'Get total size for last packet

                  Dim lastPacketDataSize As Long = fileSizeInBytes Mod chunkSize

                  'Total packet

                  Dim totalChunkPackets As Integer = Int((fileSizeInBytes / chunkSize)) + IIf(lastPacketDataSize > 0, 1, 0)

 

                  Dim completePacketData() As Byte = Nothing

                  completePacketData = New Byte(chunkSize - 1) {}

                  Dim countPacket As Integer = 0

                  Dim chunkSequenceNumber As Integer

                  Dim chunkPacketToWrite() As Byte

                  Dim dataToRead As Long = iStream.Length

 

                  While dataToRead > 0

                        If countPacket = totalChunkPackets - 1 Then

                              'Special handle for last packet of data due to the data size could less than 50 KB

                              Dim lastPacketData() As Byte = Nothing

                              lastPacketData = New Byte(lastPacketDataSize - 1) {}

                              fileLength = iStream.Read(lastPacketData, 0, lastPacketDataSize)

                              chunkPacketToWrite = lastPacketData

                        Else

                              'Read chunk data and assign as [complete packet]

                              fileLength = iStream.Read(completePacketData, 0, chunkSize)

                              chunkPacketToWrite = completePacketData

                        End If

 

                        'Upload chunk

                        With binaryData

                              .Sequence = New EntityBinary.EntityInteger With {.Value = countPacket, .IsDirty = True}

                              .Data = New EntityBinary.EntityObject With {.Value = chunkPacketToWrite, .IsDirty = True}

                        End With

                        binaryData = binaryClient.Save(binaryData)

                        chunkSequenceNumber = binaryData.Sequence.Value

 

                        If Not String.IsNullOrEmpty(chunkSequenceNumber) Then

                              dataToRead = dataToRead - fileLength

                              'Count total packet

                              countPacket += 1

                        Else

                              'Count total packet

                              countPacket -= 1

                        End If

                  End While

            End Using

 

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

      End Try

      Next

 

      '*** Call Document Attachment Service ***

      Try

      Dim docAttachmentData As New EntityDocumentAttachment.DocumentAttachmentData

      With docAttachmentData

            If Len(txtDocumentAttachmentID.Text) > 0 Then

                  .ID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocumentAttachmentID.Text), .IsDirty = True}

            End If

            .AttachmentFileName = New EntityDocumentAttachment.EntityString With {.Value = Path.GetFileName(fileInfo.FullName), .IsDirty = True}

            .AttachmentFileExtension = New EntityDocumentAttachment.EntityString With {.Value = fileInfo.Extension, .IsDirty = True}

            .DocumentID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocID.Text), .IsDirty = True}

            .MessageID = New EntityDocumentAttachment.EntityGuid With {.Value = binaryData.MessageID.Value, .IsDirty = True}

      End With

 

      Select Case operation.ToLower

            Case "create"

                  docAttachmentData = docAttachmentClient.Create(docAttachmentData)

                  MessageBox.Show("Document Attachment created successfully")

            Case "save"

                  docAttachmentData = docAttachmentClient.Save(docAttachmentData)

                  MessageBox.Show("Document Attachment saved successfully")

            Case "update"

                  docAttachmentClient.Update(docAttachmentData)

                  MessageBox.Show("Document Attachment updated successfully")

      End Select

 

      'Assign document attachment id return from service

      If Not docAttachmentData.ID.Value.Equals(System.Guid.Empty) Then

            txtDocumentAttachmentID.Text = docAttachmentData.ID.Value.ToString

      End If

      'Assign value return from service to respective text box in document attachment information section

      txtAttachmentFileName.Text = docAttachmentData.AttachmentFileName.Value

      txtAttachmentFileExtension.Text = docAttachmentData.AttachmentFileExtension.Value

      txtDocID2.Text = docAttachmentData.DocumentID.Value.ToString

      txtVersionNumber.Text = docAttachmentData.VersionNumber.Value

 

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
      End Try

  • Add code in <Create> button using the above created standard function. You can create a multiple attachment function by calling the Create operation multiple times (Attachment ID must be blank). Click button to create an item by including:

Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click

      UploadOperation("Create")
End Sub

  • Add code in <Save> button using the above created standard function. You can create multiple attachments by calling the Save operation multiple times if Attachment ID is blank, otherwise it will update the existing document attachment.
    Click button to create an item by including:

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

      UploadOperation("Save")
End Sub

  • Add code in <Update> button using the above created standard function. (Attachment ID cannot be blank).
    Click button to create an item by including:

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click

      UploadOperation("Update")
End Sub

  • Add code in <Delete> button. We need Document Attachment ID to delete a document attachment.
    Click button to create an item by including:

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

      Try

            Dim docAttachmentData As New EntityDocumentAttachment.DocumentAttachmentData

            With docAttachmentData

                  'Existing Document Attachment ID

                  .ID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocumentAttachmentID.Text), .IsDirty = True}

            End With

            docAttachmentClient.Delete(docAttachmentData)

            MessageBox.Show("Document attachment deleted successfully")

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

      End Try
End
Sub

  • You can always go back Exact Synergy Enterprise to verify that the document attachment has already been uploaded, updated or deleted successfully.



  • Add code in <Retrieve> button. We need Document Attachment ID to retrieve information about Document Attachment information.
    Click button to create an item by including:

Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click

      Try

            Dim docAttachmentData As New EntityDocumentAttachment.DocumentAttachmentData

            With docAttachmentData

                  .ID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocumentAttachmentID.Text), .IsDirty = True}

            End With

            docAttachmentData = docAttachmentClient.Retrieve(docAttachmentData)

 

            'Assign value return from service to respective text box in document attachment information section

            txtAttachmentFileName.Text = docAttachmentData.AttachmentFileName.Value

            txtAttachmentFileExtension.Text = docAttachmentData.AttachmentFileExtension.Value

            txtDocID2.Text = docAttachmentData.DocumentID.Value.ToString

            txtVersionNumber.Text = docAttachmentData.VersionNumber.Value

            MessageBox.Show("Document attachment retrieved successfully")

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

      End Try
End
Sub

  • Add code in <Validate> button. Click button to create an item by including:

Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidate.Click

      Try

            Dim docAttachmentData As New EntityDocumentAttachment.DocumentAttachmentData

            If Not String.IsNullOrEmpty(txtDocumentAttachmentID.Text) Then

                  docAttachmentData.ID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocumentAttachmentID.Text), .IsDirty = True}

            Else

                  docAttachmentData.ID = New EntityDocumentAttachment.EntityGuid With {.IsDirty = True, .IsNothing = True}

            End If

            If Not String.IsNullOrEmpty(txtDocID.Text) Then

                  docAttachmentData.DocumentID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocID.Text), .IsDirty = True}

            Else

                  docAttachmentData.DocumentID = New EntityDocumentAttachment.EntityGuid With {.IsDirty = True, .IsNothing = True}

            End If

            If Not String.IsNullOrEmpty(txtAttachmentFileName.Text) Then

                  docAttachmentData.AttachmentFileName = New EntityDocumentAttachment.EntityString With {.Value = txtAttachmentFileName.Text, .IsDirty = True}

            Else

                  docAttachmentData.AttachmentFileName = New EntityDocumentAttachment.EntityString With {.IsDirty = True, .IsNothing = True}

            End If

            docAttachmentData = docAttachmentClient.Validate(docAttachmentData)

            MessageBox.Show("Document Attachment validated successfully")

 

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

      End Try
End
Sub

  • Add code in <Download> button. In order to download a document attachment, you need to call the retrieve operation of the Document Attachment service and set the PrepareDownload value to True. After that, you need to call the retrieve operation of the Binary service to download binary data chunk by chunk and finally combine the chunks as a complete attachment. Click button to create an item by including:

Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click

      Try

            'Call Document Attachment Service: Retrieve operation with PrepareDownload = True

            Dim docAttachmentData As New EntityDocumentAttachment.DocumentAttachmentData

            With docAttachmentData

                  .ID = New EntityDocumentAttachment.EntityGuid With {.Value = New Guid(txtDocumentAttachmentID.Text), .IsDirty = True}

                  'Set to DOWNLOAD MODE *** very important flag for download ***

                  .PrepareDownload = New EntityDocumentAttachment.EntityBoolean With {.Value = True, .IsDirty = True}

            End With

            docAttachmentData = docAttachmentClient.Retrieve(docAttachmentData)

 

            'Download path

            txtDownloadPath.Text = "C:\" & docAttachmentData.AttachmentFileName.Value

            Dim fs As New FileStream(txtDownloadPath.Text, FileMode.OpenOrCreate, FileAccess.Write)

            Dim writer As BinaryWriter = New BinaryWriter(fs)

 

            'Call Binary Service:Retrieve to download binary data chunk by chunk

            Dim binaryData As New EntityBinary.BinaryData

            binaryData.MessageID = New EntityBinary.EntityGuid With {.Value = docAttachmentData.MessageID.Value, .IsDirty = True}

            Dim sequence As Integer = 0

            binaryData.Sequence = New EntityBinary.EntityInteger With {.Value = sequence, .IsDirty = True}

            binaryData = binaryClient.Retrieve(binaryData)

 

            Dim chunk As Byte()

            chunk = binaryData.Data.Value

            While Not IsNothing(chunk)

                  writer.Write(chunk, 0, chunk.Length)

                  writer.Flush()

                  chunk = Nothing

                  sequence = sequence + 1

                  binaryData.Sequence = New EntityBinary.EntityInteger With {.Value = sequence, .IsDirty = True}

                  binaryData = binaryClient.Retrieve(binaryData)

                  chunk = binaryData.Data.Value

                  'Check if data is EOF (End Of File)

                  If IsNothing(binaryData.Data.Value) Then Exit While

            End While

 

            writer.Close()

            fs.Close()

 

            'Assign value return from service to respective text box in document attachment information section

            txtAttachmentFileName.Text = docAttachmentData.AttachmentFileName.Value

            txtAttachmentFileExtension.Text = docAttachmentData.AttachmentFileExtension.Value

            txtDocID2.Text = docAttachmentData.DocumentID.Value.ToString

            txtVersionNumber.Text = docAttachmentData.VersionNumber.Value

            MessageBox.Show("Document Attachment downloaded successfully")

 

      Catch ex As Exception

            MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

      End Try
End
Sub

  1. You can also add a Try-Catch statement to catch the fault exception during the CRUDOVS operations.

          Exception:

Try

Catch ex As Exception

      MessageBox.Show("Error Occurred :" & ex.Message, "Entity Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

With blank Document ID, click <Validate> button, you will see a general exception information.



 

Fault Exception:

In order to use fault exception, you need to import <System.ServiceModel> by adding the following line at the beginning of your code:
Imports System.ServiceModel

Create a standard fault exception handling function using the code as below:

Private Sub ShowError(ByVal exc As Object)

      Dim fe As Object

      Select Case True

            Case InStr(exc.GetType.ToString, "EntityBinary")

                  fe = DirectCast(exc, FaultException(Of EntityBinary.EntityFault))

            Case InStr(exc.GetType.ToString, "EntityDocumentAttachment")

                  fe = DirectCast(exc, FaultException(Of EntityDocumentAttachment.EntityFault))

      End Select

 

      Dim sb As New System.Text.StringBuilder

      sb.AppendLine("An error has occured!")

      sb.AppendLine("")

      sb.AppendFormat("{0}: [{1}]" & vbCrLf, "Exception Type", fe.Code.Name)

      sb.AppendFormat("{0}: [{1}]" & vbCrLf, "Exception Message", fe.Message)

      sb.AppendLine("")

 

      If Not IsNothing(fe.Detail.Exceptions) AndAlso UBound(fe.Detail.Exceptions) > -1 Then

            For Each info In fe.Detail.Exceptions

                  With sb

                        .AppendFormat("{0}: [{1}]" & vbCrLf, "Property", info.PropertyName)

                        .AppendFormat("{0}: [{1}]" & vbCrLf, "Message", info.Message)

                        .AppendLine("")

                  End With

            Next

      End If

      MessageBox.Show(sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Sub

 

Try

Catch fe As FaultException

      ShowError(fe)

End Try

With blank Document ID, click <Validate> button, you will see more detailed exception information:

Related document

     
 Main Category: Support Product Know How  Document Type: Online help main
 Category: On-line help files  Security  level: All - 0
 Sub category: General  Document ID: 18.982.107
 Assortment:  Date: 03-02-2010
 Release:  Attachment:
 Disclaimer

Attachments
BinaryDemo.zip 188.6 KB Download